<script setup lang="ts">
import { ref } from 'vue'
import { isEmpty } from '@/utils/validate'
import { ElMessage } from 'element-plus'
import { getCaptchaImage } from '@/api/interface/web/user'

interface Props {
  phone: string
}

const props = defineProps<Props>()

const defaultText = '发送验证码'

const messageText = ref(defaultText)
const messageDisable = ref(false)

let clock: any = null
let time = 60

const getMessage = async () => {
  if (messageDisable.value) return
  const tel: any = props.phone
  if (isEmpty(tel)) {
    ElMessage({
      message: '请先输入手机号',
      grouping: true,
      type: 'error',
    })
    return
  }
  if (clock) return
  messageDisable.value = true
  try {
    messageText.value = `${time}秒后可重新获取`
    clock = setInterval(() => {
      time--
      messageText.value = `${time}秒后可重新获取`
      if (time === 0) {
        clearInterval(clock)
        clock = null
        messageText.value = defaultText
        messageDisable.value = false
        time = 60
      }
    }, 1000)
    await getCaptchaImage({ phone: tel })
  } catch {
    clearInterval(clock)
    clock = null
    messageText.value = defaultText
    messageDisable.value = false
    time = 60
  }
}
</script>

<template>
  <div class="short-message-wrapper" :class="{ disabled: messageDisable }" @click="getMessage">
    {{ messageText }}
  </div>
</template>

<style lang="scss" scoped>
.short-message-wrapper {
  font-family: 'PingFangSC-Regular';
  font-weight: 400;
  font-size: 18px;
  color: var(--theme-color);
  text-decoration: underline;
  cursor: pointer;
  &.disabled {
    color: rgba(144, 147, 154, 1);
  }
}
</style>
